package moviles.comprap;

import moviles.mundo.Comprap;
import moviles.mundo.Producto;
import moviles.mundo.Tienda;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.comprap.R;

public class VerProductos extends Activity {
	
	private Spinner spCategoria;	
	private ListView listaProductos;
	private ListView listaTiendas;
	private ArrayAdapter<String> adapterCategoria;
	private ArrayAdapter<String> adapterListas;
	private Spinner listas;
	private EditText textCantidad;
	private Producto product;
	private Tienda tienda;
	private String listaSelected;
	private Context context = this;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_ver_productos);
		inicializarDatos();		
	}	
	
	private void inicializarDatos(){
		listaProductos= null;
		listas = null;
		listaTiendas = null;
		textCantidad = null;
		tienda = null;
		spCategoria = (Spinner)findViewById(R.id.spinnerVerCategorias);
		adapterCategoria = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
		adapterCategoria.addAll(Comprap.darInstancia().getCategoriasToString());
		       		
		spCategoria.setAdapter(adapterCategoria);	
		spCategoria.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
	        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
	        	actualizar();
	        }
	        public void onNothingSelected(AdapterView<?> parent) {
	        }
	    });		
	}	
	
	//Actualiza la lista
	public void actualizar()
	{
		//Toast.makeText(this,"Selecciono: "+spCategoria.getSelectedItem(), Toast.LENGTH_SHORT).show();
		listaProductos = (ListView)findViewById(R.id.listView1);		
		listaProductos.setAdapter(new ProductoItemAdapter(this, android.R.layout.simple_list_item_1, Comprap.darInstancia().buscarCategoria((String)spCategoria.getSelectedItem()).getProductos()));
			
		listaProductos.setClickable(true);
		listaProductos.setOnItemClickListener(new AdapterView.OnItemClickListener() {

		  @Override
		  public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
		    Producto o = (Producto)listaProductos.getItemAtPosition(position);
		    product = o;
		    showDialog(o.getNombreProducto(),"",o);		    
		  }
		});		
	}	
	
	private int getFlagResource(String teamName) {
	    int resId = this.getResources().getIdentifier(teamName, "drawable",this.getPackageName());
	    if(resId != 0){
	        return resId;
	    }
	    return R.drawable.ic_launcher;
		}
	
	public void showDialog(String title, String message,Producto pro) {
				
		final Dialog dialog = new Dialog(this);
		dialog.setContentView(R.layout.producto_dialog_msg);
		dialog.setTitle(title);
	
         TextView text = (TextView) dialog.findViewById(R.id.textView1);
         text.setText(""+pro.getPrecio());
         TextView text2 = (TextView) dialog.findViewById(R.id.textView4);
         text2.setText(""+pro.getDescripcion());     
         ImageView img = (ImageView) dialog.findViewById(R.id.imageView1);         
         img.setImageResource(getFlagResource(pro.getImage()+"_xx"));         
         
         textCantidad = (EditText) dialog.findViewById(R.id.editText1);
         textCantidad.setText("1");
   
         listas = (Spinner)dialog.findViewById(R.id.spinner1);
         adapterListas = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,Comprap.darInstancia().getListasToString());
         listas.setAdapter(adapterListas);
         listas.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
 	        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
 	        	String o = (String)listas.getSelectedItem();  
	 		    if (o.equals("<Crear Lista>")) {					
	 		    	showDialogLista();	 		    	
	 		    }}
 	        public void onNothingSelected(AdapterView<?> parent) {
 	        }
 	    });		                 
         
        //boton de agregar a lista
        Button agregar = (Button) dialog.findViewById(R.id.button1);
        agregar.setOnClickListener(new OnClickListener() {
        @Override
            public void onClick(View v) {
        		listaSelected = (String)listas.getSelectedItem();
        		if (textCantidad.getText().toString().equals(""))
        		{        			      			
        			Toast.makeText(context,"Ingrese la cantidad del producto", Toast.LENGTH_SHORT).show();
        		}else{
        			if(textCantidad.getText().toString().matches("[0-9]+")&&textCantidad.getText().toString().length()<4) {
        				dialog.dismiss();        		
                		seleccionarTienda();
        			} else {
        				Toast.makeText(context,"Cantidad no valida", Toast.LENGTH_SHORT).show();
        			}  
        		}
        		;}
             });
        
        Button atras = (Button) dialog.findViewById(R.id.button2);
        atras.setOnClickListener(new OnClickListener() {
        @Override
            public void onClick(View v) {
        		dialog.dismiss(); 
        		;}
             });
        
        dialog.show();
    }			
	
	    
    /**
     * Dialogo de seleccionar tienda
     */
    public void seleccionarTienda() 
	{
    	listaTiendas = new ListView(this);	
    	    	
    	final AlertDialog d = new AlertDialog.Builder(this)
        .setView(listaTiendas)
        .setTitle("Seleccionar Tienda")
        .setPositiveButton(android.R.string.ok, null) //Set to null. We override the onclick
        .setNegativeButton(android.R.string.cancel, null)
        .create();
	    
	    listaTiendas.setAdapter(new TiendaItemAdapter(this, android.R.layout.simple_list_item_1, Comprap.darInstancia().darTiendasDeProducto(product)));
	    listaTiendas.setClickable(true);
	    listaTiendas.setOnItemClickListener(new AdapterView.OnItemClickListener() {
		  @Override
		  public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
			  tienda = (Tienda)listaTiendas.getItemAtPosition(position);
			  Toast.makeText(context,""+tienda.getNombreTienda()+" seleccionada", Toast.LENGTH_SHORT).show();			  
		  }
		});	
	    
	    
	    d.setOnShowListener(new DialogInterface.OnShowListener() {

	        @Override
	        public void onShow(DialogInterface dialog) {

	            Button b = d.getButton(AlertDialog.BUTTON_POSITIVE);
	            b.setOnClickListener(new View.OnClickListener() {

	                @Override
	                public void onClick(View view) {
	                	if (tienda==null){ Toast.makeText(context,"Seleccione una tienda", Toast.LENGTH_SHORT).show();}
	                	else{
	                	Comprap.darInstancia().agregarProducto(listaSelected,product,Integer.parseInt(textCantidad.getText().toString()),tienda);     
	                	exitoso(); 
	                    d.dismiss();}
	                }
	            });            
	        }
	    });
	    
	  d.show();
		
	}
    
        
	
	
	public void exitoso()
	{		Toast.makeText(this,"Producto agregado a la lista", Toast.LENGTH_SHORT).show();   
	}
	
	public void actualizarListas()
	{
		adapterListas = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,Comprap.darInstancia().getListasToString());
		listas.setAdapter(adapterListas);
	}
	
	public void showDialogLista()
	{
		final EditText input = new EditText(this);		
		AlertDialog.Builder dialogoLista = new AlertDialog.Builder(this);
		dialogoLista.setTitle("Crear lista");
	    dialogoLista.setMessage("Nombre lista");
	    dialogoLista.setView(input);	
	    dialogoLista.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
	    	@Override    
	    	public void onClick(DialogInterface dialog, int whichButton) {
	                Comprap.darInstancia().createLista((String)input.getText().toString());
	                actualizarListas();
	    	}
	       });
	       dialogoLista.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int whichButton) {
	                   // Do nothing.
	            }
	       });
	    dialogoLista.show();	
	    }
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_ver_productos, menu);
		return true;
	}		
	
	//Botones inferiores
	
	public void buscador(View v) {
		onSearchRequested();
    }
	
	public void opciones(View v) {
		finish();
    	Intent intent = new Intent(this, Opciones.class);
    	startActivity(intent);
    }
	
	public void usuario(View v) {
		finish();
    	Intent intent = new Intent(this, Usuario.class);
    	startActivity(intent);
    }
	
	public void home(View v) {
		finish();
		Intent intent = new Intent(this, MainActivity.class);
    	startActivity(intent);
    }
	public void verListas(View v) {finish();
	Intent intent = new Intent(this, VerListas.class);
	startActivity(intent);
}
	
}
